<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <SmForm
      class="-mb-15px"
      ref="formRef"
      isCol
      label-width="150px"
      v-model="formData"
      v-loading="formLoading"
      :options="requestFormOptions"
      :getModelValue="getFormData"
    >
      <!-- <template #roleItems>角色权限进行插槽展示</template> -->
    </SmForm>

    <template #footer>
      <el-button @click="submitFormDB" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { createUser, getRoleList, getUser, updateUser } from "@/api/user";
import { addProperty } from "@/components/SmForm/src/utils";
import { createDBFn } from "@/utils/decorate";
import { defaultProps } from "@/utils/tree";
import {
  getDeptList,
  getOrganizationList,
  getProvinceCityDistrictList,
  getUserList,
} from "@/commonData";
import { phoneRules } from "@/commonData/rules";
import { certTypeList, enableList, genderList, userTypeList } from "@/commonData/dict";
import { mockForm } from "@/utils/mock";
import { mockArr } from "../hooks/mock";
import CustomersAPI from "@/api/custom/customers";

/** 仓库 表单 */
defineOptions({ name: "OpenForm" });

const { t } = useI18n(); // 国际化

const dialogVisible = ref(false); // 弹窗的是否展示
const dialogTitle = ref(""); // 弹窗的标题
const formLoading = ref(false); // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref(""); // 表单的类型：create - 新增；update - 修改
const initFormData = () => {
  return {};
};
const formData = ref(initFormData());
const formRef = ref(); // 表单 Ref
const organizationList = ref([]);
const userList = ref([]);

const { provinceList, cityList, districtList, changeCity, changeProvince } =
  getProvinceCityDistrictList(formData, formRef);

const requestFormOptions: any = ref([]);
const createRequestFormOptions = () => {
  const list = [
    /**
     * 1-agentUserId-代理人userid getUserList-必填-1
       2-address-详细地址-1
       3-出生日期-birthday-1
       4-certNumber-证件号码必填-1
       5-certType-证件类型-自己弄个map-1
       6-province-省
       7-city-市
       8-district-区县
      9-customerName-客户全名-必填-1
      10-gender-性别 0:空 1:男 2:女-1
      11-orgNo-机构编号-1
     */

    {
      requiredFlag: true,
      type: "select",
      placeholder: "代理人",
      label: "代理人",
      prop: "agentUserId",
      attrs: {
        filterable: true,
        clearable: true,
        style: {
          width: "100%",
        },
      },
      children: userList,
    },

    {
      type: "select",
      placeholder: "证件类型",
      label: "证件类型",
      prop: "certType",
      attrs: {
        filterable: true,
        clearable: true,
        style: {
          width: "100%",
        },
      },
      children: certTypeList,
    },

    {
      requiredFlag: true,
      type: "input",
      label: "证件号码",
      prop: "certNumber",
      placeholder: "证件号码",
      attrs: {
        style: { width: "100%" },
        clearable: true,
      },
    },

    {
      requiredFlag: true,
      type: "input",
      label: "客户姓名",
      prop: "customerName",
      placeholder: "客户姓名",
      attrs: {
        style: { width: "100%" },
        clearable: true,
      },
    },

    {
      type: "date-picker",
      placeholder: "出生日期",
      prop: "birthday",
      label: "出生日期",
      attrs: {
        clearable: true,
        type: "date",
        "value-format": "YYYY-MM-DD", // YYYY-MM-DD HH:mm:ss
        class: "!w-1/1",
        style: {
          width: "100%",
        },
      },
    },

    // 省市区

    {
      type: "select",
      placeholder: "省",
      prop: "province",
      label: "省",
      attrs: {
        filterable: true,
        clearable: true,
        style: {
          width: "100%",
        },
        onChange: changeProvince,
      },
      children: provinceList,
    },
    {
      type: "select",
      placeholder: "市",
      prop: "city",
      label: "市",
      attrs: {
        filterable: true,
        clearable: true,
        style: {
          width: "100%",
        },
        onChange: changeCity,
      },
      children: cityList,
    },
    {
      type: "select",
      placeholder: "区",
      prop: "district",
      label: "区",
      attrs: {
        filterable: true,
        clearable: true,
        style: {
          width: "100%",
        },
      },
      children: districtList,
    },
    {
      type: "input",
      label: "详细地址",
      prop: "address",
      placeholder: "详细地址",
      attrs: {
        style: { width: "100%" },
        clearable: true,
      },
    },
    {
      type: "select",
      placeholder: "性别",
      label: "性别",
      prop: "gender",
      attrs: {
        filterable: true,
        clearable: true,
        style: {
          width: "100%",
        },
      },
      children: genderList,
    },

    {
      requiredFlag: true,
      type: "tree-select",
      placeholder: "归属机构",
      prop: "orgNo",
      label: "归属机构",
      attrs: {
        filterable: true,
        clearable: true,
        // data: mockTreeList,
        data: organizationList,
        // props: defaultProps,
        "check-strictly": true,
        // "node-key": "id",
      },
    },

    // {
    //   slot: "roleItems",
    //   label: "角色权限-插槽",
    // },
  ];

  addProperty(list);
  return list;
};

// const createRequestFormOptions = () => {
//   return mockForm(mockArr);
// };

requestFormOptions.value = createRequestFormOptions();

/** 打开弹窗 */
const open = async (type: string, id?: string) => {
  dialogVisible.value = true;
  dialogTitle.value = t("action." + type);
  formType.value = type;
  resetForm();

  getOrganizationList(organizationList);
  getUserList(userList);

  // 修改时，设置数据
  if (id) {
    formLoading.value = true;
    try {
      formData.value = await CustomersAPI.getInfo(id);
      // 主动触发表单数据回显
      formRef.value.initForm();
    } finally {
      formLoading.value = false;
    }
  }
};
defineExpose({ open }); // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(["success"]); // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate();
  // 提交请求
  formLoading.value = true;
  try {
    const data = formData.value as unknown as any;
    if (formType.value === "create") {
      await CustomersAPI.create(data);
    } else if (formType.value === "update") {
      await CustomersAPI.update(data.id, data);
    }
    ElMessage.success("操作成功");
    dialogVisible.value = false;
    // 发送操作成功的事件
    emit("success");
  } finally {
    formLoading.value = false;
  }
};
const submitFormDB = createDBFn(submitForm);

/** 重置表单 */
const resetForm = () => {
  formData.value = initFormData();
  formRef.value?.resetFields();
};

const getFormData = () => {
  return formData.value;
};
</script>
